import os
import datetime
import logging
from flask import Blueprint, jsonify
from app.config.paths import ASSEMBLY_EOL_ROOT

assembly_eol_bp = Blueprint('assembly_eol', __name__)

logger = logging.getLogger(__name__)
if not logger.handlers:
    logging.basicConfig(level=logging.INFO, format='[%(asctime)s] %(levelname)s %(name)s: %(message)s')

FAIL_TOKENS = ('NG', 'FAIL', 'NOK', 'ERROR', 'FAILED', 'REJECT')
PASS_TOKENS = ('PASS', 'OK', 'GOOD', 'ACCEPT')


@assembly_eol_bp.route('/query/<path:sn>', methods=['GET'])
def query_sn(sn: str):
    sn = (sn or '').strip()
    if not sn:
        return jsonify({'code': 400, 'message': '缺少 sn 参数', 'data': None}), 400

    root_dir = ASSEMBLY_EOL_ROOT
    today_dir = os.path.join(root_dir, datetime.datetime.now().strftime('%Y-%m-%d'))
    logger.info('assembly_eol query: sn=%s dir=%s', sn, today_dir)

    if not os.path.isdir(root_dir):
        return jsonify({'code': 404, 'message': f'目录不存在: {root_dir}', 'data': None}), 404
    if not os.path.isdir(today_dir):
        return jsonify({'code': 404, 'message': f'当日目录不存在: {today_dir}', 'data': None}), 404

    try:
        files = []
        for name in os.listdir(today_dir):
            lower = name.lower()
            # 仅遍历 .csv 文件
            print("name:",name)

            logger.info('name=%s', name)

            if lower.endswith('.csv'):
                full = os.path.join(today_dir, name)
                try:
                    print("full:",full)
                    mtime = os.path.getmtime(full)
                except Exception:
                    mtime = 0
                files.append((full, mtime))
        files.sort(key=lambda x: x[1], reverse=True)
    except Exception as e:
        logger.exception('listdir failed: %s', e)
        return jsonify({'code': 500, 'message': f'目录读取失败: {e}', 'data': None}), 500

    encodings = ['utf-8', 'utf-8-sig', 'gbk', 'gb2312', 'utf-16', 'utf-16-le', 'utf-16-be', 'latin1']

    for full, _ in files:
        for enc in encodings:
            try:
                with open(full, 'r', encoding=enc, errors='ignore') as fh:
                    for idx, line in enumerate(fh, start=1):
                        if sn not in line:
                            continue
                        upper = line.upper()
                        status = None
                        if any(t in upper for t in FAIL_TOKENS):
                            status = False
                        elif any(t in upper for t in PASS_TOKENS):
                            status = True
                        return jsonify({
                            'code': 200,
                            'message': 'success',
                            'data': {
                                'sn': sn,
                                'found': True,
                                'is_pass': status,
                                'file': full,
                                'line_no': idx,
                                'line': line.strip()
                            }
                        })
                break
            except OSError:
                continue
            except Exception as e:
                logger.warning('read file failed %s enc=%s: %s', full, enc, e)
                continue

    return jsonify({'code': 200, 'message': 'not found', 'data': {'sn': sn, 'found': False, 'is_pass': None}})
